package com.snap.vseries.model;

import android.content.ContentValues;

import com.snap.vseries.bean.ExpEntity;

import org.litepal.LitePal;
import org.litepal.crud.callback.CountCallback;
import org.litepal.crud.callback.FindCallback;
import org.litepal.crud.callback.FindMultiCallback;
import org.litepal.crud.callback.SaveCallback;
import org.litepal.crud.callback.UpdateOrDeleteCallback;
import org.litepal.tablemanager.Connector;

import java.util.List;

class DBModel {

    DBModel() {
        Connector.getDatabase();
    }

    //=============================👇同步方法👇==================================
    //保存模板 同步！！！
    boolean saveDemoSync(ExpEntity demo) {
        return demo.saveOrUpdate("testProject = ? and isTemplate= 1", demo.getTestProject());
    }

    //保存实验 同步！！！
    boolean saveExpSync(ExpEntity experiment) {
        return experiment.saveOrUpdate("name = ? and isTemplate= 0", experiment.getName());
    }

    //=============================👇模板👇==================================

    //获取模板列表
    void getTemplateList(FindMultiCallback<ExpEntity> callback) {
        LitePal.where("isTemplate=1")
                .order("sortId asc")
                .findAsync(ExpEntity.class)
                .listen(callback);
    }

    //同步方法，获取模板列表
    List<ExpEntity> getTemplateList() {
        List<ExpEntity> entityList = LitePal.where("isTemplate=1")
                .order("sortId asc")
                .find(ExpEntity.class);
        return entityList;
    }

    //保存模板 异步！！！
    void saveTemplate(ExpEntity experiment, SaveCallback callback) {
        experiment.saveOrUpdateAsync("name = ? and isTemplate=1", experiment.getTestProject())
                .listen(callback);
    }

    //保存模板 同步！！！
    boolean saveTemplate(ExpEntity experiment) {
        boolean result = experiment.saveOrUpdate("testProject=? and isTemplate=1", experiment.getTestProject());
        return result;
    }

    //保存模板 同步！！！
    boolean saveTemplateList(List<ExpEntity> experiment) {
        return LitePal.saveAll(experiment);
    }


    //=============================👇实验👇==================================
    //保存实验
    void saveExp(ExpEntity experiment, SaveCallback callback) {
        experiment.saveOrUpdateAsync("name = ? and isTemplate= 0", experiment.getName())
                .listen(callback);
    }

    //获取实验列表
    void getExpList(int limit, FindMultiCallback<ExpEntity> callback) {
        LitePal.where("isTemplate= 0")
                .order("startTime desc")
                .limit(limit)
                .findAsync(ExpEntity.class)
                .listen(callback);
    }

    //收藏实验（单个，多个）
    void collectExp(UpdateOrDeleteCallback callback, String... name) {
        if (name.length == 0) {
            callback.onFinish(0);
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("'").append(name[0]).append("'");
        for (int i = 1; i < name.length; i++) {
            sb.append(",").append("'").append(name[i]).append("'");
        }
        String whereClause = String.format("isTemplate= 0 and isCollect= 0 and name in (%s)", sb.toString());
        ContentValues values = new ContentValues();
        values.put("isCollect", "1");
        LitePal.updateAllAsync(ExpEntity.class, values, whereClause)
                .listen(callback);
    }

    //删除实验（单个，多个）
    void deleteExp(UpdateOrDeleteCallback callback, String... name) {
        if (name.length == 0) {
            callback.onFinish(0);
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("'").append(name[0]).append("'");
        for (int i = 1; i < name.length; i++) {
            sb.append(",").append("'").append(name[i]).append("'");
        }
        String whereClause = String.format("isTemplate= 0 and name in (%s)", sb.toString());
        LitePal.deleteAllAsync(ExpEntity.class, whereClause)
                .listen(callback);
    }

    //删除实验（单个，多个）
    void deleteTemplate(UpdateOrDeleteCallback callback, String... name) {
        if (name.length == 0) {
            callback.onFinish(0);
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("'").append(name[0]).append("'");
        for (int i = 1; i < name.length; i++) {
            sb.append(",").append("'").append(name[i]).append("'");
        }
        String whereClause = String.format("isTemplate= 1 and testProject in (%s)", sb.toString());
        LitePal.deleteAllAsync(ExpEntity.class, whereClause)
                .listen(callback);
    }

    //删除实验（单个，多个）
    void deleteTemplate(String... name) {
        if (name.length == 0) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("'").append(name[0]).append("'");
        for (int i = 1; i < name.length; i++) {
            sb.append(",").append("'").append(name[i]).append("'");
        }
        String whereClause = String.format("isTemplate= 1 and testProject in (%s)", sb.toString());
        LitePal.deleteAll(ExpEntity.class, whereClause);
    }

    //多条件查询实验数目
    void getExpCount(String name, CountCallback callback) {
        LitePal.select()
                .where("isTemplate= 0   and name like ?", "%" + name + "%")
                .countAsync(ExpEntity.class)
                .listen(callback);
    }

    //多条件查询实验（分页）
    void getExp(String name, int offset, int limit, FindMultiCallback<ExpEntity> callback) {
        LitePal.select()
                .where("isTemplate= 0   and name like ?", "%" + name + "%")
                .order("startTime desc")
                .offset(offset)
                .limit(limit)
                .findAsync(ExpEntity.class).listen(callback);
    }

    //多条件查询实验（分页）
    List<ExpEntity> getExpSync(String name, int offset, int limit) {
        List<ExpEntity> entityList = LitePal.select()
                .where("isTemplate= 0   and name like ?", "%" + name + "%")
                .order("startTime desc")
                .offset(offset)
                .limit(limit)
                .find(ExpEntity.class);
        return entityList;
    }

    //获取全部实验
    void getAllExp(FindMultiCallback<ExpEntity> callback) {
        LitePal.select()
                .where("isTemplate= 0")
                .order("startTime desc")
                .findAsync(ExpEntity.class).listen(callback);
    }

    //根据名称查找实验
    void getExpByName(String name, FindCallback<ExpEntity> callback) {
        LitePal.select()
                .where("name = ? and isTemplate= 0", name)
                .findFirstAsync(ExpEntity.class)
                .listen(callback);
    }

    //根据名称查找模板
    void getTemplateByName(String name, FindCallback<ExpEntity> callback) {
        LitePal.select()
                .where("name = ? and isTemplate= 1", name)
                .findFirstAsync(ExpEntity.class)
                .listen(callback);
    }
}
